//
// Created by yyancy on 2019/10/31.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#include "udp.c"
#include "unp.h"

//#define SA struct sockaddr *
int datalen = 28;
char sendbuf[1500];


uint16_t in_cksum(uint16_t *addr, int len) {
    int nleft = len;
    uint32_t sum = 0;
    uint16_t *w = addr;
    uint16_t answer = 0;

    while (nleft > 1) {
        sum += *w++;
        nleft -= 2;
    }

    if (nleft == 1) {
        *(unsigned char *) (&answer) = *(unsigned char *) w;
        sum += answer;
    }
    sum = (sum >> 16) + (sum & 0xffff);
    sum += (sum >> 16);
    answer = ~sum;
    return (answer);
}

int server() {
    struct sockaddr_in server_sock;
    struct sockaddr_in client_sock;

    int server_fd;
    int client_fd;
    socklen_t clien_sock_len;
    char buf[100];
    char *mes = "hello,world";

    server_sock.sin_family = PF_INET;
//    server_sock.sin_addr.s_addr = htonl("INADDR_ANY");
    server_sock.sin_addr.s_addr = inet_addr("1.1.1.1");
    server_sock.sin_port = htons(8080);

    client_sock.sin_family = PF_INET;
//    client_sock.sin_addr.s_addr = htonl(INADDR_ANY);
    client_sock.sin_addr.s_addr = inet_addr("1.1.1.1");
//    client_sock.sin_port = htons(8080);

    server_fd = Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
//    Bind(server_fd, (SA) &server_sock, sizeof(server_sock));
    struct icmp* icmp;
    icmp = (struct icmp*)sendbuf;
    int isent = getpid();
    icmp->icmp_type = ICMP_ECHO;
    icmp->icmp_code = 0;
    icmp->icmp_id = 1;
    icmp->icmp_seq = isent++;

    memset(icmp->icmp_data, 0xa5, datalen);
    int len = 8 + datalen;
    icmp->icmp_cksum = 0;
    icmp->icmp_cksum = in_cksum((u_short *) icmp, len);

    if(sendto(server_fd, sendbuf, len, 0, (SA) &client_sock, sizeof(client_sock)) == -1){
        perror("can not send icmp package!");
    }


//    close(client_fd);
    close(server_fd);

    return 0;
}



int main() {
    setuid(getuid());
    server();
    return 0;
}